package com.log.log.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
* AS2 
 * @param
* @author yangshuanglong
* @date 2024/8/1
* {@link null}
* return null
* @description 获取实体注解中的名称作为返回列
 *
*/

public class AnnotationUtils {

    // 缓存表字段名到Java字段名的映射
    private static final Map<Class<?>, Map<String, String>> columnToFieldCache = new HashMap<>();
    private static final Map<Class<?>, String> tableNameCache = new HashMap<>();

    public static String getFieldNameByColumnName(Class<?> clazz, String columnName) {
        // 从缓存中获取映射
        Map<String, String> columnToFieldMap = columnToFieldCache.computeIfAbsent(clazz, AnnotationUtils::buildColumnToFieldMap);
        return columnToFieldMap.get(columnName);
    }

    public static Map<String, String> buildColumnToFieldMap(Class<?> clazz) {
        Map<String, String> columnToFieldMap = new HashMap<>();
        Field[] fields = clazz.getDeclaredFields();
        //获取注解中定义数据库的字段，和实体的变量名称
        for (Field field : fields) {
            //获取字段上的注解
            TableField tableField = field.getAnnotation(TableField.class);
            if (tableField != null) {
                //以注解名称作为key，字段名为value
                columnToFieldMap.put(tableField.value(), field.getName());
            }
        }

        return columnToFieldMap;
    }
    public static String getTableName(Class<?> clazz) {
        // 从缓存中获取表名
        return tableNameCache.computeIfAbsent(clazz, AnnotationUtils::extractTableName);
    }

    private static String extractTableName(Class<?> clazz) {
        //获取类注解上定义的数据库表名
        TableName table = clazz.getAnnotation(TableName.class);
        if (table != null) {
            return table.value();
        }
        return null;
    }
}
